<?php

namespace app\ajax\controller;

use app\common\controller\Base;
use think\Image;

class Upload extends Base
{

    /**
     * @return array
     * 原点 2020年7月10日16:35:35 上传压缩图片
     */
    public function upload_images()
    {

        $file = request()->file('file');
        $size = config('upload_img_size')*1024*1024;
        //再次验证上传大小以及后缀是否为图片格式，仅支持'gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf';可以自行更改
        $check = $file->validate(['size' => $size, 'ext' => ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf']])->check();
        if(!$check) return ['code'=>1,'msg'=>$file->getError()];
        //利用图片处理类进行压缩上传
        $image = Image::open($file);
        $path = ROOT_PATH . 'public' . DS . 'uploads' . DS . date("Ym");
        $file_name = date('YmdHis') . rand(1000, 9999);
        if(!is_dir($path)){
            mkdir(iconv("UTF-8", "GBK", $path),0777,true);
        }
        $flag = $image->save($path . DS . $file_name . '.'.$image->type(),null,config('upload_img_quality'),true);
        if($flag){
            return ['code'=>0,'msg'=>'上传成功','data'=>[
                'src' =>'/uploads/'. date("Ym") . '/' . $file_name . '.'.$image->type()
            ]];
        }else{
            return ['code'=>1,'msg'=>'上传出错：'.$file->getError()];
        }

    }

    /**
     * @return array
     * 上传文件，还是原方法，
     */
    public function upload_file(){
        $files = request()->file();
        foreach($files as $file){
            $file_info = $file->getInfo();
            $info = $file->move(ROOT_PATH.'public'.DS.'uploads'.DS.date("Ym").'/video', date('YmdHis').rand(1000,9999));
            $msg = [];
            if($info){
                $msg['code'] = 0;
                $msg['data'] = [
                    'src'=>'/uploads/'.date("Ym").'/'.$info->getSaveName(),
                    'file_name'=>$file_info['name'],
                    'title'=>'/public/uploads/'.$info->getSaveName()
                ];
                $msg['msg'] = "上传成功";
                return json($msg);
                if(input('u_id')){
                    //插入签到视频
                    
                }
            }else{
                // 上传失败获取错误信息
                $msg['code'] = 1;
                $msg['msg'] = "上传出错";
                return json($msg);
            }
        }
    }
}